package com.learn.project2.service.admin.coupon;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.learn.project2.bean.MarketCoupon;
import com.learn.project2.bean.MarketCouponExample;
import com.learn.project2.mapper.MarketCouponMapper;
import com.learn.project2.model.bo.admin.coupon.CouponCreateBO;
import com.learn.project2.model.bo.admin.coupon.CouponListBO;
import com.learn.project2.model.bo.admin.coupon.CouponUpdateBO;
import com.learn.project2.model.vo.admin.coupon.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.learn.project2.bean.MarketCouponUser;
import com.learn.project2.bean.MarketCouponUserExample;
import com.learn.project2.mapper.MarketCouponUserMapper;
import com.learn.project2.model.bo.admin.coupon.CouponDeleteBO;
import com.learn.project2.utils.BaseParam;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.MathContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhizhuke 岳子昂
 * @version 1.0
 * @description:
 * @date 2022-01-08 08-45
 */
@Service
@CacheConfig(cacheNames = {"marketCoupon"})
public class CouponServiceImpl implements CouponService {

    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;


    /**
     * @description:
     * @author zhizhuke
     * @date 2022-01-08 08-46
     * @version 1.0
     */
//    @Cacheable
    @Override
    public CouponListVO list(BaseParam param, String name, Integer type, Integer status) {
        Integer page = param.getPage();
        Integer limit = param.getLimit();
        PageHelper.startPage(page, limit);

        MarketCouponExample example = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        if (type != null) {
            criteria.andTypeEqualTo(type.shortValue());
        }
        if (status != null) {
            criteria.andStatusEqualTo(status.shortValue());
        }
        criteria.andDeletedEqualTo(false);
        example.setOrderByClause((param.getSort() + " ") + param.getOrder() + "");
        List<MarketCoupon> list = couponMapper.selectByExample(example);

        PageInfo<MarketCoupon> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        List<CouponListInnerVO> voList = new ArrayList<>();
        for (MarketCoupon coupon : list) {
            CouponListInnerVO innerVO = new CouponListInnerVO(coupon.getId(), coupon.getName(), coupon.getDesc(), coupon.getTag(), coupon.getTotal(),
                    coupon.getDiscount(), coupon.getMin(), coupon.getLimit(), coupon.getType(), coupon.getStatus(), coupon.getGoodsType(),
                    coupon.getGoodsValue(), coupon.getTimeType(), coupon.getDays(), coupon.getAddTime(), coupon.getUpdateTime(),
                    coupon.getDeleted());
            voList.add(innerVO);
        }
        return new CouponListVO(((int) total), pages, limit, page, voList);
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author 岳子昂
     * @date: 2022-01-08 01:44
     */
    @Override
    @Transactional
    public CouponCreateVO create(CouponCreateBO couponCreateBO) {
        String name = couponCreateBO.getName();
        String desc = couponCreateBO.getDesc();
        String tag = couponCreateBO.getTag();

//        Integer total = couponCreateBO.getTotal();
        String totalStr = couponCreateBO.getTotal();
        int total = Integer.parseInt(totalStr);

        String discountStr = couponCreateBO.getDiscount();
//        int discountInt = Integer.parseInt(discountStr);
        BigDecimal discount = new BigDecimal(discountStr);

        String minStr = couponCreateBO.getMin();
//        int minInt = Integer.parseInt(minStr);
        BigDecimal min = new BigDecimal(minStr);

//        Short limit = couponCreateBO.getLimit();
        String limitStr = couponCreateBO.getLimit();
        short limit = Short.parseShort(limitStr);


        Short type = couponCreateBO.getType();
        Short status = couponCreateBO.getStatus();
        Short goodsType = couponCreateBO.getGoodsType();
        Integer[] goodsValue = couponCreateBO.getGoodsValue();
        Short timeType = couponCreateBO.getTimeType();

//        Short days = couponCreateBO.getDays();
        String daysStr = couponCreateBO.getDays();
        short days = Short.parseShort(daysStr);


        Date startTime = couponCreateBO.getStartTime();
        Date endTime = couponCreateBO.getEndTime();

        MarketCoupon marketCoupon = new MarketCoupon();
        marketCoupon.setDeleted(false);
        marketCoupon.setName(name);
        marketCoupon.setDesc(desc);
        marketCoupon.setTag(tag);
        marketCoupon.setTotal(total);
        marketCoupon.setDiscount(discount);
        marketCoupon.setMin(min);
        marketCoupon.setLimit(limit);
        marketCoupon.setType(type);
        // 如果type为按照兑换码分发，就随机生成一段兑换码，赋值给code，放入数据库
        if (type == 2){
            String code = RandomStringUtils.randomAlphanumeric(8);
            marketCoupon.setCode(code);
        }

        if (timeType == 1){
            Date nowTime = new Date();
            Calendar date = Calendar.getInstance();
            date.setTime(nowTime);

            Calendar end = Calendar.getInstance();
            end.setTime(endTime);

            // 如果当前时间处在结束时间之前，statu就是0， 处在结束时间之后，statu就是1
            if (date.after(end)){
                marketCoupon.setStatus(((short) 1));
            }else {
                marketCoupon.setStatus(((short) 0));
            }
        }

        marketCoupon.setGoodsType(goodsType);
        marketCoupon.setGoodsValue(goodsValue);
        marketCoupon.setTimeType(timeType);
        marketCoupon.setDays(days);
        marketCoupon.setStartTime(startTime);
        marketCoupon.setEndTime(endTime);



        marketCoupon.setAddTime(new Date());
        marketCoupon.setUpdateTime(new Date());

        couponMapper.insert(marketCoupon);

        Integer id = marketCoupon.getId();
        CouponCreateVO vo = new CouponCreateVO();
        vo.setId(id);
        vo.setName(name);
        vo.setDesc(desc);
        vo.setTag(tag);
        vo.setTotal(total);
        vo.setDiscount(discount);
        vo.setMin(min);
        vo.setLimit(limit);
        vo.setType(type);
        vo.setStatus(marketCoupon.getStatus());
        vo.setGoodsType(goodsType);
        vo.setGoodsValue(goodsValue);
        vo.setTimeType(timeType);
        vo.setDays(days);
        vo.setStartTime(startTime);
        vo.setEndTime(endTime);
        vo.setAddTime(marketCoupon.getAddTime());
        vo.setUpdateTime(marketCoupon.getUpdateTime());

        return vo;
    }


    /**
     * @description:
     * @param:
     * @return:
     * @author 岳子昂
     * @date: 2022-01-08 01:44
     */
    @Override
    @Transactional
    public CouponUpdateVO update(CouponUpdateBO couponUpdateBO) {
        // 接收bo中的数据
        Integer id = couponUpdateBO.getId();
        String name = couponUpdateBO.getName();
        String desc = couponUpdateBO.getDesc();
        String tag = couponUpdateBO.getTag();

        //        Integer total = couponCreateBO.getTotal();
        String totalStr = couponUpdateBO.getTotal();
        int total = Integer.parseInt(totalStr);

        String discountStr = couponUpdateBO.getDiscount();
//        int discountInt = Integer.parseInt(discountStr);
        BigDecimal discount = new BigDecimal(discountStr);

        String minStr = couponUpdateBO.getMin();
//        int minInt = Integer.parseInt(minStr);
        BigDecimal min = new BigDecimal(minStr);

//        Short limit = couponCreateBO.getLimit();
        String limitStr = couponUpdateBO.getLimit();
        short limit = Short.parseShort(limitStr);

        Short type = couponUpdateBO.getType();
        Short status = couponUpdateBO.getStatus();
        Short goodsType = couponUpdateBO.getGoodsType();
        Integer[] goodsValue = couponUpdateBO.getGoodsValue();
        Short timeType = couponUpdateBO.getTimeType();

        //        Short days = couponCreateBO.getDays();
        String daysStr = couponUpdateBO.getDays();
        short days = Short.parseShort(daysStr);

        Date startTime = couponUpdateBO.getStartTime();
        Date endTime = couponUpdateBO.getEndTime();
        Date addTime = couponUpdateBO.getAddTime();

        // 将bo中的数据放进POJO
        MarketCoupon marketCoupon = new MarketCoupon();
        marketCoupon.setDeleted(false);
        marketCoupon.setId(id);
        marketCoupon.setName(name);
        marketCoupon.setDesc(desc);
        marketCoupon.setTag(tag);
        marketCoupon.setTotal(total);
        marketCoupon.setDiscount(discount);
        marketCoupon.setLimit(limit);
        marketCoupon.setMin(min);
        marketCoupon.setType(type);
        // 如果type为按照兑换码分发，就随机生成一段兑换码，赋值给code，放入数据库
        if (type == 2){
            String code = RandomStringUtils.randomAlphanumeric(8);
            marketCoupon.setCode(code);
        }


        if (timeType == 1){
            Date nowTime = new Date();
            Calendar date = Calendar.getInstance();
            date.setTime(nowTime);

            Calendar end = Calendar.getInstance();
            end.setTime(endTime);

            // 如果当前时间处在结束时间之前，statu就是0， 处在结束时间之后，statu就是1
            if (date.after(end)){
                marketCoupon.setStatus(((short) 1));
            }else {
                marketCoupon.setStatus(((short) 0));
            }
        }

        marketCoupon.setGoodsType(goodsType);
        marketCoupon.setGoodsValue(goodsValue);
        marketCoupon.setTimeType(timeType);
        marketCoupon.setDays(days);
        marketCoupon.setStartTime(startTime);
        marketCoupon.setEndTime(endTime);
        marketCoupon.setAddTime(addTime);
        marketCoupon.setUpdateTime(new Date());

        // 根据POJO更新数据库
        couponMapper.updateByPrimaryKey(marketCoupon);

        // 根据POJO获取返回vo
        CouponUpdateVO vo = new CouponUpdateVO();
        vo.setId(id);
        vo.setName(name);
        vo.setDesc(desc);
        vo.setTag(tag);
        vo.setTotal(total);
        vo.setDiscount(discount);
        vo.setMin(min);
        vo.setLimit(limit);
        vo.setType(type);
        vo.setStatus(marketCoupon.getStatus());
        vo.setGoodsType(goodsType);
        vo.setGoodsValue(goodsValue);
        vo.setTimeType(timeType);
        vo.setDays(days);
        vo.setStartTime(startTime);
        vo.setEndTime(endTime);
        vo.setAddTime(addTime);
        vo.setUpdateTime(marketCoupon.getUpdateTime());
        return vo;
    }

    @Override
    public CouponReadVO read(Integer id) {
        MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(id);
        String name = marketCoupon.getName();
        String desc = marketCoupon.getDesc();
        String tag = marketCoupon.getTag();
        Integer total = marketCoupon.getTotal();
        BigDecimal discount = marketCoupon.getDiscount();
        BigDecimal min = marketCoupon.getMin();
        Short limit = marketCoupon.getLimit();
        Short type = marketCoupon.getType();
        Short status = marketCoupon.getStatus();
        Short goodsType = marketCoupon.getGoodsType();
        Integer[] goodsValue = marketCoupon.getGoodsValue();
        Short timeType = marketCoupon.getTimeType();
        Short days = marketCoupon.getDays();
        Date addTime = marketCoupon.getAddTime();
        Date updateTime = marketCoupon.getUpdateTime();
        Boolean deleted = marketCoupon.getDeleted();

        CouponReadVO couponReadVO = new CouponReadVO();

        couponReadVO.setId(id);
        couponReadVO.setName(name);
        couponReadVO.setDesc(desc);
        couponReadVO.setTag(tag);
        couponReadVO.setTotal(total);
        couponReadVO.setDiscount(discount);
        couponReadVO.setMin(min);
        couponReadVO.setLimit(limit);
        couponReadVO.setType(type);
        couponReadVO.setStatus(status);
        couponReadVO.setGoodsType(goodsType);
        couponReadVO.setGoodsValue(goodsValue);
        couponReadVO.setTimeType(timeType);
        couponReadVO.setDays(days);
        couponReadVO.setAddTime(addTime);
        couponReadVO.setUpdateTime(updateTime);
        couponReadVO.setDeleted(deleted);

        return couponReadVO;
    }

    /**
     * @description:
     * @author zhizhuke
     * @date 2022-01-08 08-46
     * @version 1.0
     */
    @Transactional
    @Override
    public void delete(CouponDeleteBO couponDeleteBO) {
        MarketCoupon coupon = new MarketCoupon();
        coupon.setId(couponDeleteBO.getId());
        coupon.setDeleted(true);
        couponMapper.updateByPrimaryKeySelective(coupon);
    }

    /**
     * @description:
     * @author zhizhuke
     * @date 2022-01-08 08-46
     * @version 1.0
     */
 //   @Cacheable
    @Override
    public CouponListUserVO listuser(BaseParam param, Integer couponId) {

        //分页查询
        Integer page = param.getPage();
        Integer limit = param.getLimit();
        PageHelper.startPage(page, limit);

        MarketCouponUserExample example = new MarketCouponUserExample();
        example.createCriteria().andCouponIdEqualTo(couponId).andDeletedEqualTo(false);
        example.setOrderByClause((param.getSort() + " ") + param.getOrder() + "");
        List<MarketCouponUser> list = couponUserMapper.selectByExample(example);

        //获取分页信息
        PageInfo<MarketCouponUser> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();


        return new CouponListUserVO((int) total, pages, limit, page, list);
    }


}
